package com.ruoyi.web.controller.V2.goodInfo.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.V2.goodInfo.domain.ExportJYMGoods;
import com.ruoyi.system.V2.goodInfo.service.IGoodsInfoService;
import com.ruoyi.system.model.domain.GoodsInfo;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueReq;
import com.ruoyi.system.model.exel.GoodsInfoExecl;
import com.ruoyi.system.model.exel.gameExcel.CFExcel;
import com.ruoyi.system.model.exel.gameExcel.LOLExcel;
import com.ruoyi.system.model.exel.gameExcel.YSExcel;
import com.ruoyi.system.model.vo.DeleteAllVo;
import com.ruoyi.system.service.ISysUserService;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * goodsController
 *
 * @author ruoyi
 * @date 2023-04-06
 */
@RestController
@RequestMapping("/goods/info")
public class GoodsInfoController extends BaseController {
    @Autowired
    private IGoodsInfoService goodsInfoService;
    @Autowired
    private ISysUserService userService;

    /**
     * 查询goods列表
     */
    @GetMapping("/list")
    public TableDataInfo list(GoodsInfo goodsInfo) {
        startPage();
        List<GoodsInfo> list = goodsInfoService.selectGoodsInfoList(goodsInfo);
        return getDataTable(list);
    }

    /**
     * 查询goods列表
     */
    @GetMapping("/todayDetail")
    public AjaxResult todayDetail() {
        HashMap result = goodsInfoService.todayDetail();
        return AjaxResult.success(result);
    }

    /**
     * 导出goods列表
     */
    @Log(title = "goods", businessType = BusinessType.EXPORT)
    @PostMapping("/exportJYM")
    public AjaxResult exportJYM(@RequestBody GoodsInfo goodsInfoAndAttrValueReq) {
        List<ExportJYMGoods> exportJYMGoods = goodsInfoService.selectExportJYM(goodsInfoAndAttrValueReq);
        ExcelUtil<ExportJYMGoods> util = new ExcelUtil<ExportJYMGoods>(ExportJYMGoods.class);
        AjaxResult result = util.exportExcel(exportJYMGoods, "goods数据");
        return result;
    }

    /**
     * 导出goods列表
     */
    @Log(title = "goods", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(GoodsInfoAndAttrValueReq goodsInfoAndAttrValueReq) {
        PageDomain pageDomain = TableSupport.buildPageRequest();

        List<GoodsInfo> list = goodsInfoService.selectByResList(goodsInfoAndAttrValueReq, pageDomain);
        List<GoodsInfoExecl> execlList = new ArrayList<>();
        for (GoodsInfo goodsInfo : list) {
            GoodsInfoExecl goodsInfoExecl = new GoodsInfoExecl();
            BeanUtils.copyProperties(goodsInfo, goodsInfoExecl);
            execlList.add(goodsInfoExecl);
        }
        ExcelUtil<GoodsInfoExecl> util = new ExcelUtil<GoodsInfoExecl>(GoodsInfoExecl.class);
        AjaxResult result = util.exportExcel(execlList, "goods数据");
//        return util.exportExcel(execlList, "goods数据",7);

        try {
            if (!FileUtils.checkAllowDownload(result.get("msg").toString())) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", result.get("msg").toString()));
            }
            String filePath = RuoYiConfig.getDownloadPath() + result.get("msg").toString();
            File file = new File(filePath);
            JSONObject req = new JSONObject();
            req.put("file", new FileInputStream(file));
            req.put("game_id", 12);
            req.put("user_id", 496786);

            System.out.println(req.toJSONString());

            if (true) {
//                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
        }
        return result;
    }

    /**
     * 导出goods列表
     */
    @Log(title = "goods", businessType = BusinessType.EXPORT)
    @GetMapping("/exportPX")
    public AjaxResult exportPX(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueReq) {

        goodsInfoAndAttrValueReq.setDel(0l);
        Long gameId = goodsInfoAndAttrValueReq.getGameId();
        if (gameId != null) {
            List<GoodsInfoAndAttrValueDto> goodslist = goodsInfoService.selectGoodsInfoAndAttrList(goodsInfoAndAttrValueReq);
            if (gameId == 4l) {
                List<YSExcel> execlList = new ArrayList<>();
                for (GoodsInfoAndAttrValueDto dto : goodslist) {
                    YSExcel excel = new YSExcel();
                    excel.setAccount(dto.getAccountNumber());
                    excel.setPassword(dto.getAccountPassword());
                    excel.setPrice(dto.getPrice().multiply(new BigDecimal("0.85")).setScale(0,
                            BigDecimal.ROUND_FLOOR));
                    if ("哔哩哔哩".equals(dto.getCarrierName())) {
                        excel.setGroupName(2);
                    } else if ("游戏官方".equals(dto.getCarrierName())) {
                        excel.setGroupName(1);
                    } else {
                        excel.setGroupName(3);
                    }
                    int emailState = 0;
                    String shiming = "A";
                    if ("39117".equals(dto.getF2())) {
                        emailState = 3;
                    } else if ("39118".equals(dto.getF2())) {
                        emailState = 1;
                        shiming = "B";
                    } else if ("39119".equals(dto.getF2())) {
                        emailState = 1;
                    } else if ("39120".equals(dto.getF2())) {
                        emailState = 5;
                    } else if ("39121".equals(dto.getF2())) {
                        emailState = 6;
                    } else if ("39123".equals(dto.getF2())) {
                        emailState = 2;
                        shiming = "B";
                    } else {
                        emailState = 1;
                    }
                    excel.setEmailState(emailState);

                    excel.setShiming(shiming);
                    if ("38947".equals(dto.getF4())) {
                        excel.setIsPsn(1);
                    } else {
                        excel.setIsPsn(0);
                    }
                    if ("38950".equals(dto.getF5())) {
                        excel.setIsTap(1);
                    } else {
                        excel.setIsTap(0);
                    }
                    excel.setIsSync(1);
                    excel.setRemark(dto.getTitle());

                    execlList.add(excel);
                }
                ExcelUtil<YSExcel> util = new ExcelUtil<>(YSExcel.class);
                return util.exportExcel(execlList, "原神goods数据");
            }
            if (gameId == 5l) {//LOL
                List<LOLExcel> execlList = new ArrayList<>();
                for (GoodsInfoAndAttrValueDto dto : goodslist) {
                    LOLExcel excel = new LOLExcel();
                    excel.setAccount(dto.getAccountNumber());
                    excel.setPassword(dto.getAccountPassword());
                    excel.setPrice(dto.getPrice().multiply(new BigDecimal("0.85")).setScale(0,
                            BigDecimal.ROUND_FLOOR));
                    excel.setGroupName(dto.getGroupName());
                    excel.setService(dto.getServerName());
                    if ("39494".equals(dto.getF1())) {
                        excel.setShiming(1);
                    } else {
                        excel.setShiming(0);
                    }

                    excel.setRemark(dto.getTitle());
                    execlList.add(excel);
                }
                ExcelUtil<LOLExcel> util = new ExcelUtil<>(LOLExcel.class);
                return util.exportExcel(execlList, "LOLgoods数据");
            }
            if (gameId == 8l) {
                List<CFExcel> execlList = new ArrayList<>();
                for (GoodsInfoAndAttrValueDto dto : goodslist) {
                    CFExcel excel = new CFExcel();
                    excel.setAccount(dto.getAccountNumber());
                    excel.setPassword(dto.getAccountPassword());
                    excel.setPrice(dto.getPrice().multiply(new BigDecimal("0.85")).setScale(0,
                            BigDecimal.ROUND_FLOOR));
                    int system = 0;
                    if ("安卓".equals(dto.getSystemName())) {
                        if ("QQ".equals(dto.getCarrierName())) {
                            system = 1;
                        } else {
                            system = 2;
                        }
                    } else {
                        if ("QQ".equals(dto.getCarrierName())) {
                            system = 6;
                        } else {
                            system = 63;
                        }
                    }

                    excel.setSystem(system);
                    if ("41659".equals(dto.getF10())) {
                        excel.setShiming(80);
                    } else if ("41660".equals(dto.getF10())) {
                        excel.setShiming(178);
                    } else {
                        excel.setShiming(81);
                    }
                    excel.setRemark(dto.getTitle());
                    execlList.add(excel);
                }
                ExcelUtil<CFExcel> util = new ExcelUtil<>(CFExcel.class);
                return util.exportExcel(execlList, "CFMgoods数据");
            }
        } else {
            throw new GlobalException("请选择游戏!");
        }
        List<GoodsInfoExecl> execlList = new ArrayList<>();
        PageDomain pageDomain = TableSupport.buildPageRequest();
        GoodsInfoAndAttrValueReq req = new GoodsInfoAndAttrValueReq();
        BeanUtils.copyProperties(req, goodsInfoAndAttrValueReq);
        List<GoodsInfo> list = goodsInfoService.selectByResList(req, pageDomain);
        for (GoodsInfo goodsInfo : list) {
            GoodsInfoExecl goodsInfoExecl = new GoodsInfoExecl();
            BeanUtils.copyProperties(goodsInfo, goodsInfoExecl);
            execlList.add(goodsInfoExecl);
        }
        ExcelUtil<GoodsInfoExecl> util = new ExcelUtil<GoodsInfoExecl>(GoodsInfoExecl.class);
        return util.exportExcel(execlList, "goods数据");
    }

    /**
     * 获取goods详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(goodsInfoService.selectGoodsInfoAndAttrValueById(id));
    }

    /**
     * 新增goods
     */
    @Log(title = "goods", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto) {
        goodsInfoAndAttrValueDto.setAccountType(1); //走发布的 都属于自营
        goodsInfoAndAttrValueDto.setSaleState(10); //新增默认 待审核
        return toAjax(goodsInfoService.insertGoodsInfoAndAttr(goodsInfoAndAttrValueDto));
    }

    /**
     * 修改goods
     */
    @Log(title = "goods", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto) {
        return toAjax(goodsInfoService.updateGoodsInfoAndAttr(goodsInfoAndAttrValueDto));
    }

    /**
     * 删除游戏账号
     */
    @Log(title = "全部删除", businessType = BusinessType.DELETE)
    @GetMapping("/deleteAllAccount")
    public AjaxResult deleteAllAccount(DeleteAllVo deleteAllVo) {
        return toAjax(goodsInfoService.deleteAllAccount(deleteAllVo));
    }

    /**
     * 批量删除
     */
    @Log(title = "goods", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(goodsInfoService.deleteGoodsInfoByIds(ids));
    }

    /**
     * 批量删除
     */
    @Log(title = "goods", businessType = BusinessType.DELETE)
    @GetMapping("down/{ids}")
    public AjaxResult down(@PathVariable Long[] ids) {
        return toAjax(goodsInfoService.down(ids));
    }

    @Log(title = "上架商品", businessType = BusinessType.UPDATE)
    @GetMapping("/upGoods/{id}")
    public AjaxResult upGoods(@PathVariable("id") Long id) {
        return toAjax(goodsInfoService.upGoodsById(id));
    }

    @Log(title = "上架商品", businessType = BusinessType.UPDATE)
    @PutMapping("/upGoods/two")
    public AjaxResult upGoodsTwo(Long id, String problemDes) {
        GoodsInfoAndAttrValueDto dto = new GoodsInfoAndAttrValueDto();
        dto.setId(id);
        dto.setProblemDes(problemDes);
        return toAjax(goodsInfoService.upGoodsById(dto));
    }

    @Log(title = "重置掉绑状态", businessType = BusinessType.UPDATE)
    @GetMapping("/resetUnbind/{id}")
    public AjaxResult resetUnbind(@PathVariable("id") Long id) {
        return toAjax(goodsInfoService.resetUnbindById(id));
    }

    @Log(title = "下架商品", businessType = BusinessType.UPDATE)
    @PostMapping("/downGoods")
    public AjaxResult downGoods(@RequestBody GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto) {
        return toAjax(goodsInfoService.downGoodsById(goodsInfoAndAttrValueDto));
    }

    @Log(title = "转为已售", businessType = BusinessType.UPDATE)
    @GetMapping("/toSaled/{id}")
    public AjaxResult toSaled(@PathVariable("id") Long id) {
        return toAjax(goodsInfoService.toSaled(id));
    }

    @Log(title = "置顶", businessType = BusinessType.UPDATE)
    @GetMapping("/toTop/{id}")
    public AjaxResult toTop(@PathVariable("id") Long id) {
        return toAjax(goodsInfoService.toTop(id));
    }

    @Log(title = "转为问题号", businessType = BusinessType.UPDATE)
    @PostMapping("/problemGoods")
    public AjaxResult problemGoods(@RequestBody GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto) {
        return toAjax(goodsInfoService.problemGoods(goodsInfoAndAttrValueDto));
    }

    @Log(title = "转为找回号", businessType = BusinessType.UPDATE)
    @PostMapping("/retrieveGoods")
    public AjaxResult retrieveGoods(@RequestBody GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto) {
        return toAjax(goodsInfoService.retrieveGoods(goodsInfoAndAttrValueDto));
    }

    @Log(title = "审核", businessType = BusinessType.UPDATE)
    @GetMapping("/auditGoods/{ids}")
    public AjaxResult auditGoods(@PathVariable Long[] ids) {
        return toAjax(goodsInfoService.auditGoods(ids));
    }

    @Log(title = "提号", businessType = BusinessType.UPDATE)
    @GetMapping("/submitAccount/{ids}")
    public AjaxResult submitAccount(@PathVariable Long[] ids) {
        return toAjax(goodsInfoService.submitAccount(ids));
    }


    @Log(title = "提号V2", businessType = BusinessType.UPDATE)
    @PostMapping("/submitAccount")
    public AjaxResult submitAccount(@RequestBody JSONObject params) {
        return toAjax(goodsInfoService.submitAccount(params));
    }

    /**
     * @param params
     * @return
     */
    @Log(title = "修改提号备注", businessType = BusinessType.UPDATE)
    @PostMapping("/updateRemake")
    public AjaxResult updateRemake(@RequestBody JSONObject params) {
        return toAjax(goodsInfoService.updateRemake(params));
    }


    /**
     * 查询goods列表
     */
    @GetMapping("/allList")
    public TableDataInfo allList(GoodsInfoAndAttrValueReq goodsInfoAndAttrValueReq) {

        PageDomain pageDomain = TableSupport.buildPageRequest();

        List<GoodsInfo> list = goodsInfoService.selectByResList(goodsInfoAndAttrValueReq, pageDomain);
        return getDataTable(list);
    }

    /**
     * 查询goods列表
     */
    @GetMapping("/myAccount")
    public TableDataInfo myAccount(GoodsInfoAndAttrValueReq goodsInfoAndAttrValueReq) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Long userId = SecurityUtils.getUserId();
        if (!Objects.equals(1l, userId)) {
            goodsInfoAndAttrValueReq.setCreateId(SecurityUtils.getUserId());
        }
        List<GoodsInfo> list = goodsInfoService.selectByResList(goodsInfoAndAttrValueReq, pageDomain);
        return getDataTable(list);
    }


    /**
     * 账号池
     *
     * @param goodsInfo
     * @return
     */
    @GetMapping("/poollist")
    public TableDataInfo poollist(GoodsInfo goodsInfo) {
        //零售客服已添加账号,账号池不需要展示
        startPage();
        goodsInfo.setSaleState(1);
        List<GoodsInfo> list = goodsInfoService.selectGoodsInfoList(goodsInfo);
        for (GoodsInfo info : list) {
            info.setAccountNumber(null);
            info.setAccountPassword(null);
            info.setSecurityPhone(null);
            SysUser sysUser = userService.selectUserById(info.getCreateId());
            if (Objects.nonNull(sysUser)) {
                info.setCreateName(sysUser.getNickName());
            }
        }
        List<SysUser> supplyCustomer = userService.getUserByRoleCode("supplyCustomer");
        goodsInfoService.bacthAddPrice(list, supplyCustomer);
        return getDataTable(list);
    }

    @GetMapping("/countForSupply")
    public AjaxResult countForSupply(GoodsInfo goodsInfo) {
        List<Map<String, Object>> list = goodsInfoService.countForSupply(goodsInfo);
        return AjaxResult.success(list);
    }

    /**
     * 修改价格
     */
    @Log(title = "goods", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/editPrice")
    public AjaxResult editPrice(@RequestBody GoodsInfo goodsInfo) {
        if (StringUtils.isNull(goodsInfo.getId())) {
            throw new GlobalException("商品id不能为空");
        }
        if (StringUtils.isNull(goodsInfo.getPrice())) {
            throw new GlobalException("修改后的价格不能为空");
        }
        GoodsInfo goodsInfoReq = new GoodsInfo();
        goodsInfoReq.setId(goodsInfo.getId());
        goodsInfoReq.setPrice(goodsInfo.getPrice());
        return toAjax(goodsInfoService.updateGoodsInfo(goodsInfoReq));
    }

    @PutMapping("/transferThePossessionOf")
    public AjaxResult allGoodsEdit(Long transferId, Long fromUserId) {
        goodsInfoService.transferThePossessionOf(transferId, fromUserId);
        return AjaxResult.success();
    }

    @PutMapping("/clone/{id}")
    public AjaxResult clone(@PathVariable("id") Long id) {
        goodsInfoService.clone(id);
        return AjaxResult.success();
    }


}
